<template>
  <div class="app-container">
    <div class="search-container">
      <el-input v-model="searchForm.name" class="search-input" placeholder="请输入部门名称" :clearable="true" />
      <el-button type="primary" icon="el-icon-search" size="small" @click="getDepList()">搜索</el-button>
      <el-button v-hasPermission="['dept_excel']" type="primary" icon="el-icon-download" size="small" @click="getExcel()">导出</el-button>
    </div>
    <div class="function-buttons" />
    <div>
      <el-table
        :data="deptList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'leaf' }"
      >
        <el-table-column prop="name" label="部门" />
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <!--                    <el-button type="text" @click="showAddResource(scope.row)">视频资源</el-button>-->
            <el-button type="text" @click="showUpdate(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="视频列表" :visible.sync="videoList.visible" :close-on-click-modal="false">
      <el-dialog title="新增视频" :visible.sync="saveVideoForm.visible" :close-on-click-modal="false" append-to-body>
        <el-form ref="saveForm" :model="saveVideoForm.props" :rules="saveVideoForm.rules" label-width="80px">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="saveVideoForm.props.sort" type="number" />
          </el-form-item>
          <el-form-item label="站点视频" prop="videoUrl">
            <el-button type="text" @click="chooseVideoDialog = true">选择视频</el-button>
            <el-button
              v-if="!!saveVideoForm.props.videoUrl"
              type="text"
              @click="saveVideoForm.props.videoUrl = null"
            >移除视频</el-button>
            <video
              v-if="!!saveVideoForm.props.videoUrl"
              class="video-preview"
              controls
              :src="cfg.imageDomain + saveVideoForm.props.videoUrl"
              alt=""
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('saveForm')">取 消</el-button>
          <el-button type="primary" @click="doSaveVideo">确 定</el-button>
        </div>
      </el-dialog>
      <el-button @click="addVideo">新增</el-button>
      <div class="el-dialog-div">
        <el-table :data="videoList.dataList" border>
          <el-table-column width="" align="center" label="排序">
            <template slot-scope="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>
          <el-table-column width="" align="center" label="资源">
            <template slot-scope="scope">
              <video :src="cfg.imageDomain + scope.row.videoUrl" controls="controls" width="300px" height="200px" />
            </template>
          </el-table-column>
          <el-table-column width="" align="center" label="展示">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="saveVideoShow(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="removeVideo(scope.row)">删除</el-button>
              <el-button v-hasPermission="['sys_dept_edit']" type="text" @click="editVideo(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="videoList.total > 0"
          :total="videoList.total"
          :current-page.sync="videoList.pageNo"
          :limit.sync="videoList.pageSize"
          @current-change="getVideoListPageChange"
        />
      </div>
    </el-dialog>
    <!-- todo 调整表单字段 -->
    <el-dialog title="编辑" :visible.sync="formData.formDialog" :close-on-click-modal="false">
      <el-dialog title="选择人员" :visible.sync="userTable.visible" :close-on-click-modal="false" append-to-body>
        <div class="search-container">
          <el-input v-model="searchUserForm.name" class="search-input" placeholder="请输入姓名" :clearable="true" />
          <el-input v-model="searchUserForm.phone" class="search-input" placeholder="请输入手机" :clearable="true" />
          <el-button type="primary" icon="el-icon-search" size="small" @click="getUserList()">搜索</el-button>
        </div>
        <el-table :data="userTable.dataList" border :row-key="getRowKeys" @selection-change="handleSelectionChange">
          <el-table-column type="selection" header-align="center" align="center" width="50" />
          <el-table-column width="" align="center" label="用户名">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column width="" align="center" label="手机号">
            <template slot-scope="scope">
              <span>{{ scope.row.tel }}</span>
            </template>
          </el-table-column>
          <el-table-column width="" align="center" label="部门">
            <template slot-scope="scope">
              <span>{{ scope.row.departmentName }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="userTable.total > 0"
          :total="userTable.total"
          :current-page.sync="userTable.pageNo"
          :limit.sync="userTable.pageSize"
          @current-change="getUserListPageChange"
        />
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveUsers">确 定</el-button>
        </span>
      </el-dialog>
      <el-form ref="saveDpetForm" :model="formData.props" :rules="formData.rules" label-width="180px">
        <el-form-item label="部门类型">
          <common-select v-model="formData.props.deptType" name="EnumDeptType" placetext="请选择菜单类型" />
        </el-form-item>
        <!--        <el-form-item label="ue区域">-->
        <!--          <common-select v-model="formData.props.ueArea" name="EnumUeAreaType" placetext="请选择ue区域" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="部门地域">-->
        <!--          <el-input v-model="formData.props.areaType" placeholder="请输入部门地域用英文逗号分隔" :clearable="true" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="所属区域">-->
        <!--          <common-select v-model="formData.props.area" name="EnumAreaType" placetext="请选择区域" />-->
        <!--        </el-form-item>-->
        <el-form-item label="经度">
          <el-input v-model="formData.props.longitude" placeholder="请输入经度" :clearable="true" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="formData.props.latitude" placeholder="请输入纬度" :clearable="true" />
        </el-form-item>
        <!--        <el-form-item label="占地面积(平方米)">-->
        <!--          <el-input v-model="formData.props.siteArea" placeholder="请输入占地面积" :clearable="true" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="是否建模">-->
        <!--          <el-switch-->
        <!--            v-model="formData.props.isModel"-->
        <!--            active-color="#13ce66"-->
        <!--            inactive-color="#ff4949"-->
        <!--            :active-value="true"-->
        <!--            :inactive-value="false"-->
        <!--            @change="formData.props.modelName = ''"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item v-if="formData.props.isModel" label="模型名称">-->
        <!--          <common-select v-model="formData.props.modelName" name="EnumModelType" placetext="请选择模型名称" />-->
        <!--        </el-form-item>-->
        <!--        &lt;!&ndash;        <el-form-item label="PoiID">&ndash;&gt;-->
        <!--        &lt;!&ndash;          <el-input v-model="formData.props.poiId" placeholder="请输入PoiID" :clearable="true" />&ndash;&gt;-->
        <!--        &lt;!&ndash;        </el-form-item>&ndash;&gt;-->
        <!--        <el-form-item label="Poi点名">-->
        <!--          <el-input v-model="formData.props.poiName" placeholder="请输入Poi点名" :clearable="true" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="负责人">-->
        <!--          <el-tag-->
        <!--            v-for="tag in formData.props.users"-->
        <!--            :key="tag.id"-->
        <!--            closable-->
        <!--            style="margin-right: 10px"-->
        <!--            @close="tagClose(tag)"-->
        <!--          >{{ tag.name }}</el-tag>-->
        <!--          <el-button type="text" @click="showUserTable">选择人员</el-button>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="描述">-->
        <!--          <el-input-->
        <!--            v-model="formData.props.describes"-->
        <!--            type="textarea"-->
        <!--            :rows="5"-->
        <!--            placeholder="请输入描述"-->
        <!--            :clearable="true"-->
        <!--          />-->
        <!--        </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="btnSubmitDisabled" @click="save">确 定</el-button>
      </span>
    </el-dialog>
    <choose-video :visible.sync="chooseVideoDialog" @choose="chooseVideo" @close="chooseVideoDialog = false" />
  </div>
</template>

<script>
import request from '@/utils/request'
import ChooseVideo from '@/components/wejoy/ChooseVideo'
import CommonSelect from '@/components/wejoy/CommonSelect'

export default {
  name: 'SysDeptList',
  components: { ChooseVideo, CommonSelect },
  data() {
    return {
      chooseVideoDialog: false,
      deptList: [],
      deptListAdd: [],
      btnSubmitDisabled: false,
      list: [],
      total: 0,
      listLoading: true,
      formData: {
        formDialog: false,
        // 表单字段, 请自行删除不需要的
        props: {
          describes: '',
          area: '',
          longitude: '',
          latitude: '',
          userId: '',
          deptType: '',
          users: [],
          PoiName: '',
          PoiId: '',
          ueArea: '',
          siteArea: '',
          isModel: false,
          modelName: '',
          areaType: ''
        },
        // 表单校验规则, 默认增加了必填, 请自行限制长度或者其他修改
        rules: {
        }
      },
      listQuery: {
        id: -1
      },
      videoList: {
        visible: false,
        dataList: [],
        pageNo: '',
        pageSize: 10,
        total: '',
        deptId: ''
      },
      userTable: {
        visible: false,
        dataList: [],
        pageNo: '',
        pageSize: 10,
        total: '',
        name: '',
        tel: ''
      },
      saveVideoForm: {
        visible: false,
        props: {
          id: '',
          sort: '',
          videoUrl: '',
          deptId: ''
        },
        rules: {
          sort: this.formRules({ required: true }),
          videoUrl: this.formRules({ required: true })
        }
      },
      noticeDeptUserList: [],
      searchForm: {
        name: ''
      },
      defaultCheckedKeys: [1],
      searchUserForm: {
        username: '',
        tel: ''
      }
    }
  },
  created() {
    this.getDepList();
  },
  methods: {
    load(tree, treeNode, resolve) {
      // var _this = this;
      request({
        url: `/system/sysDept/getDeptList`,
        method: 'post',
        data: {
          includeLower: false,
          parentId: tree.id
        }
      }).then(res => {
        setTimeout(() => {
          resolve(res.data.map(item => {
            return {
              ...item,
              leaf: !item.leaf
            };
          }))
        }, 300)
      })
    },
    removeVideo(item) {
      request({
        url: `/system/sysDeptVideo/remove`,
        method: 'post',
        params: {
          id: item.id
        }
      }).then(res => {
        this.$message.success('删除成功')
        this.getVideoListPageChange();
      })
    },
    cancel: function(formName) {
      this.$refs[formName].clearValidate();
      this.$refs[formName].resetFields();
      this.saveVideoForm.visible = false;
    },
    showUpdate: function(data) {
      request({
        url: `/system/sysDept/getOneById?id=` + data.id,
        method: 'post',
        data: {
          id: data.id
        }
      }).then(res => {
        this.formData.props = {
          id: res.data.id == null || res.data.id === '' ? data.id : res.data.id,
          area: res.data.area,
          ueArea: res.data.ueArea,
          longitude: res.data.longitude,
          latitude: res.data.latitude,
          describes: res.data.describes,
          userId: res.data.userId,
          deptType: res.data.deptType ? res.data.deptType.toString() : '-1',
          users: res.data.users,
          poiName: res.data.poiName,
          poiId: res.data.poiId,
          siteArea: res.data.siteArea,
          isModel: res.data.isModel,
          modelName: res.data.modelName,
          areaType: res.data.areaType
        }
        this.formData.formDialog = true;
      })
    },
    showAddResource(item) {
      this.videoList.visible = true
      this.saveVideoForm.props.deptId = item.id
      this.getDepVideoList(item);
    },
    saveVideoShow(item) {
      var _this = this;
      request({
        url: `/system/sysDeptVideo/save`,
        method: 'post',
        data: {
          id: item.id,
          isShow: item.isShow
        }
      }).then(res => {
        _this.$message.success('修改成功')
      })
    },
    getDepVideoList(item) {
      var _this = this;
      _this.videoList.total = '';
      _this.videoList.pageNo = 1;
      _this.videoList.deptId = item.id;
      request({
        url: `/system/sysDeptVideo/getPageList`,
        method: 'post',
        data: {
          pageNo: _this.videoList.pageNo,
          pageSize: _this.videoList.pageSize,
          deptId: _this.videoList.deptId
        }
      }).then(res => {
        _this.videoList.dataList = res.data.rows
        _this.videoList.total = res.data.total;
      })
    },
    getUserList() {
      var _this = this;
      _this.userTable.total = '';
      _this.userTable.pageNo = 1;
      request({
        url: `/system/sysUser/getPageList`,
        method: 'post',
        data: {
          pageNo: _this.userTable.pageNo,
          pageSize: _this.userTable.pageSize,
          // departmentId: 1000099,
          // 客户测试环境
          departmentId: 1000372,
          ...this.searchUserForm
        }
      }).then(res => {
        _this.userTable.dataList = res.data.rows
        _this.userTable.total = res.data.total;
      })
    },
    getUserListPageChange() {
      const _this = this;
      request({
        method: 'post',
        url: '/system/sysUser/getPageList',
        data: {
          pageNo: _this.userTable.pageNo,
          pageSize: _this.userTable.pageSize,
          // departmentId: 1000099
          // 客户测试环境
          departmentId: 1000372
        }
      }).then(res => {
        _this.userTable.dataList = res.data.rows
        _this.userTable.total = res.data.total;
      });
    },
    chooseVideo(file) {
      this.saveVideoForm.props.videoUrl = file.path;
    },
    getVideoListPageChange() {
      const _this = this;
      request({
        method: 'post',
        url: '/system/sysDeptVideo/getPageList',
        data: {
          pageNo: _this.videoList.pageNo,
          pageSize: _this.videoList.pageSize,
          deptId: _this.videoList.deptId
        }
      }).then(res => {
        _this.videoList.dataList = res.data.rows
        _this.videoList.total = res.data.total;
      });
    },
    addVideo() {
      this.saveVideoForm.props.sort = ''
      this.saveVideoForm.props.videoUrl = ''
      this.saveVideoForm.visible = true
    },
    showUserTable() {
      this.getUserList()
      this.formData.props.users = []
      this.userTable.visible = true
    },
    editVideo(item) {
      this.saveVideoForm.props.id = item.id
      this.saveVideoForm.props.videoUrl = item.videoUrl
      this.saveVideoForm.props.deptId = item.deptId
      this.saveVideoForm.props.sort = item.sort
      this.saveVideoForm.visible = true
    },
    doSaveVideo() {
      const _this = this;
      if (!_this.saveVideoForm.props.sort) {
        _this.$message.error('请填写排序');
        return
      }
      if (!_this.saveVideoForm.props.videoUrl) {
        _this.$message.error('请选择视频');
        return;
      }
      request({
        url: `/system/sysDeptVideo/save`,
        method: 'post',
        data: {
          ..._this.saveVideoForm.props
        }
      }).then(res => {
        _this.$message.success('新增成功')
        _this.saveVideoForm.visible = false
        _this.cancel('saveForm')
        _this.getVideoListPageChange();
      })
    },
    getDepList() {
      var _this = this;
      _this.deptList = []
      request({
        url: `/system/sysDept/getDeptList`,
        method: 'post',
        data: {
          // parentId: -1,
          // includeLower: false,
          ...this.searchForm
        }
      }).then(res => {
        _this.deptList = res.data.map(item => {
          return {
            ...item,
            leaf: !item.leaf
          };
        });
      })
    },
    save: function() {
      var _this = this;
      if (_this.formData.props.users) {
        const userIds = _this.formData.props.users.map(item => item.id);
        // 用 join 方法将数组连接为字符串，使用逗号分隔
        _this.formData.props.userId = userIds.join(',');
      }
      this.disableBtn(this, 'btnSubmitDisabled');
      this['$refs'].saveDpetForm.validate(function(valid) {
        if (!valid) {
          return;
        }
        request({
          url: '/system/sysDept/save',
          method: 'post',
          data: _this.formData.props
        }).then(res => {
          _this.$message.success('保存成功');
          _this.formData.formDialog = false;
        })
      });
    },
    handleSelectionChange(val) {
      console.log(this.formData.props.users);

      // 过滤掉取消选择的用户
      this.formData.props.users = this.formData.props.users.filter(user =>
        val.findIndex(row => row.id === user.id) === -1
      );

      // 将当前页的选中数据合并到总的选中数据中
      this.formData.props.users = [...this.formData.props.users, ...val];

      console.log(this.formData.props.users);
    },
    tagClose(data) {
      this.formData.props.users = this.formData.props.users.filter(item => item.id !== data.id);
    },
    getRowKeys(row) {
      return row.id
    },
    saveUsers() {
      var _this = this;
      // 用 map 方法提取 userId 属性并连接为字符串
      const userIds = _this.formData.props.users.map(item => item.id);
      // 用 join 方法将数组连接为字符串，使用逗号分隔
      _this.formData.props.userId = userIds.join(',');
      _this.userTable.visible = false
    },
    getExcel() {
      let url = `${process.env.VUE_APP_BASE_API}/system/sysDept/excel?`;
      url = url + 'parentId=' + -1;
      // 客户测试环境
      // url = url + 'parentId=' + 1000372;
      window.open(url)
    }
  }
}
</script>

<style scoped>
.video-preview {
  display: block;
  height: 200px;
  min-width: 300px;
  max-width: 500px;
}
</style>
